/* 
        apt install libjansson-dev
        apt list --installed |grep jansson

        #include <jansson.h>  // 需安装 libjansson-dev 库 apt install libjansson-dev
        sample code.
 */

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jansson.h>  // 需安装 libjansson-dev 库 apt install libjansson-dev

//examples = dealwithCmdWithArg("cmds", "channels", "$channels$", json_str)
int dealwithCmdWithArg(const char *key_cmds, const char *key_params, const char *keyword_2_replace, const char *jsonObjWithArgsInString) {
    // 原始 JSON 数据
    const char *json_str = "{"
        "\"caption\":\"xxxx\","
        "\"cmds\":[\"python3 ./tools/calc_vibration.py $channels$ &\"],"
        "\"channels\":[1,2,3]"
    "}";

    // 解析 JSON
    json_error_t error;
    json_t *root = json_loads(jsonObjWithArgsInString, 0, &error); //load from string
    if (!root) {
        fprintf(stderr, "JSON 解析错误: %s\n", error.text);
        return 1;
    }

    // 提取 channels 数组
    json_t *channels = json_object_get(root, key_params); //object .....
    if (!json_is_array(channels)) {
        fprintf(stderr, "channels 字段无效\n");
        json_decref(root);
        return 1;
    }

    // 提取 cmds 数组
    json_t *cmds = json_object_get(root, key_cmds);
    if (!json_is_array(cmds)) {
        fprintf(stderr, "cmds 字段无效\n");
        json_decref(root);
        return 1;
    }

    // 遍历 cmds 并展开命令
    for (size_t i = 0; i < json_array_size(cmds); i++) { //json array loop. array length.
        const char *cmd_template = json_string_value(json_array_get(cmds, i)); //array item fetch. item->string
        if (!cmd_template) continue;

        // 遍历每个 channel 生成命令
        for (size_t j = 0; j < json_array_size(channels); j++) {
            json_t *channel_val = json_array_get(channels, j); 
            int channel = json_integer_value(channel_val); //int value access.

            // 替换占位符
            char cmd_expanded[256];
            snprintf(cmd_expanded, sizeof(cmd_expanded), "%s", cmd_template);
            char *placeholder = strstr(cmd_expanded, keyword_2_replace);
            if (placeholder) {
                // 计算新命令长度并动态替换
                char new_cmd[1024];
                int prefix_len = placeholder - cmd_expanded;
                strncpy(new_cmd, cmd_expanded, prefix_len);
                new_cmd[prefix_len] = '\0';
                sprintf(new_cmd + prefix_len, "%d%s", channel, placeholder + strlen(keyword_2_replace));
                printf("%s\n", new_cmd);  // 输出最终命令
                system(new_cmd);
                
            }
        }
    }

    // 清理资源
    json_decref(root);
    return 0;
}